/*
 * ClientMessage.cpp
 *
 */

#include "ClientMessage.h"
#include "http/HttpCodes.h"

ClientMessage::ClientMessage(Socket* socket, const ServerConfig& config, LogFile& log, const std::string& id):
socket(socket), host(config, log), done(false), id(id), logFile(log) {}

ClientMessage::~ClientMessage() {
	delete socket;
}

const std::string& ClientMessage::getId() const {
	return id;
}

int ClientMessage::getElapsedTime() const {
	return creationTime.getElapsedTimed();
}

bool ClientMessage::finished() const {
	return done;
}

void ClientMessage::sendErrorRespone(HttpProtocol& protocol, int code) {
	try {
		HttpResponse response;
		host.errorProcess(response, code);
		protocol.sendResponse(response);
	}
	catch (const SocketException& e) {}
}

void ClientMessage::run() {
	HttpProtocol protocol(*socket);
	try {
		const HttpRequest* request = protocol.recvRequest();
		HttpResponse response;
		host.generateResponse(response, *request);
		protocol.sendResponse(response);
		socket->close();
		done = true;
	}
	catch (const MessageException& e) {
		// Request error
		sendErrorRespone(protocol, HttpCodes::BAD_REQUEST);
		socket->close();
		done = true;
	}
	catch (const SocketException& e) {
		socket->close();
		done = true;
	}
	catch (...) {
		logFile.addError("El cliente " + id + " tuvo un error inesperado.");
		socket->close();
		done = true;
	}
}

void ClientMessage::die() {
	Thread::die();
	socket->shutdown();
	host.terminate();
}
